package com.ywyt.route;

import com.rabbitmq.client.*;
import com.ywyt.util.ConnUtil;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RouteConsumer1 {
    public static final String QUEUE_ERROR = "route_error1";
    public static final String QUEUE_DEBUG = "route_debug1";

    @Test
    public void receive() throws IOException, TimeoutException {
        //获取连接对象
        Connection connection = ConnUtil.getConnection();
        //获取channel
        final Channel channel = connection.createChannel();
        /*
        * 声明绑定ERROR队列
        * */
        channel.queueDeclare(QUEUE_ERROR,false,false,false,null);
        channel.queueBind(QUEUE_ERROR,RouteProvider.EXCHANGE_NAME,RouteProvider.ERROR);
        /*
        * 声明绑定DEBUG队列
        * */
        channel.queueDeclare(QUEUE_DEBUG,false,false,false,null);
        channel.queueBind(QUEUE_DEBUG,RouteProvider.EXCHANGE_NAME,RouteProvider.DEBUG);
        //创建consumer
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("ERROR和DEBUG接收到消息" + new String(body,"UTF-8"));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(QUEUE_DEBUG,false,consumer);
        channel.basicConsume(QUEUE_ERROR,false,consumer);
        System.in.read();
        //释放资源
        channel.close();
        connection.close();
    }
}
